package com.pdd.mall.config;

import com.pdd.mall.entity.Merchant;
import com.pdd.mall.entity.Product;
import com.pdd.mall.entity.Promotion;
import com.pdd.mall.entity.PromotionProduct;
import com.pdd.mall.entity.User;
import com.pdd.mall.mapper.MerchantMapper;
import com.pdd.mall.mapper.ProductMapper;
import com.pdd.mall.mapper.PromotionMapper;
import com.pdd.mall.mapper.PromotionProductMapper;
import com.pdd.mall.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 数据初始化类
 */
@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private PromotionMapper promotionMapper;

    @Autowired
    private PromotionProductMapper promotionProductMapper;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("开始初始化数据...");

        // 初始化所有数据
        initializeAllData();

        // 添加商品原价字段
        addOriginalPriceField();

        // 所有数据初始化已通过SQL文件完成

        System.out.println("数据初始化完成");
    }

    private void addOriginalPriceField() {
        try {
            System.out.println("添加商品原价字段...");

            // 检查列是否存在
            boolean columnExists = false;
            try {
                Integer count = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM information_schema.COLUMNS " +
                    "WHERE TABLE_SCHEMA = DATABASE() " +
                    "AND TABLE_NAME = 'product' " +
                    "AND COLUMN_NAME = 'original_price'",
                    Integer.class
                );
                columnExists = (count != null && count > 0);
                System.out.println("商品原价字段" + (columnExists ? "已存在" : "不存在"));
            } catch (Exception e) {
                System.out.println("检查商品原价字段是否存在时出错: " + e.getMessage());
                // 假设列不存在
                columnExists = false;
            }

            // 如果列不存在，添加列
            if (!columnExists) {
                try {
                    jdbcTemplate.execute(
                        "ALTER TABLE `product` ADD COLUMN `original_price` decimal(10,2) DEFAULT NULL " +
                        "COMMENT '商品原价（促销前的价格）' AFTER `price`"
                    );
                    System.out.println("成功添加商品原价字段");
                } catch (Exception e) {
                    // 忽略列已存在的错误
                    if (e.getMessage().toLowerCase().contains("duplicate") ||
                        e.getMessage().toLowerCase().contains("already exists") ||
                        (e.getCause() != null && e.getCause().getMessage().toLowerCase().contains("duplicate"))) {
                        System.out.println("商品原价字段已存在，无需添加: " + e.getMessage());
                    } else {
                        throw e;
                    }
                }
            }

            // 更新现有商品的原价为当前价格
            try {
                int updatedRows = jdbcTemplate.update(
                    "UPDATE `product` SET `original_price` = `price` WHERE `original_price` IS NULL"
                );
                System.out.println("更新了 " + updatedRows + " 个商品的原价");
            } catch (Exception e) {
                System.err.println("更新商品原价失败: " + e.getMessage());
                e.printStackTrace();
            }

            System.out.println("添加商品原价字段完成");
        } catch (Exception e) {
            System.err.println("添加商品原价字段失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void initializeAllData() {
        try {
            // 读取合并后的SQL文件内容
            ClassPathResource resource = new ClassPathResource("db/init_all.sql");
            String sql = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);

            // 执行SQL语句
            String[] statements = sql.split(";");
            for (String statement : statements) {
                if (!statement.trim().isEmpty()) {
                    try {
                        jdbcTemplate.execute(statement);
                    } catch (Exception e) {
                        // 忽略CREATE DATABASE和USE语句可能出现的错误
                        if (!e.getMessage().contains("CREATE DATABASE") && !e.getMessage().contains("USE")) {
                            throw e;
                        }
                    }
                }
            }

            // 添加商品原价字段
            addOriginalPriceField();
            
            System.out.println("数据初始化完成");
        } catch (Exception e) {
            System.err.println("初始化数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }




}
